<template>
  <v-chart
    :style="style"
    :option="widget.option"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>
<script>
import { renderWidgetData } from "../tools/DataUtils";
export default {
  props: {
    widget: {
      type: [Object],
      default: () => {},
    },
  },
  data() {
    return {
      render: null,
    };
  },
  computed: {
    style() {
      return {
        width: this.widget.location.width + "px",
        height: this.widget.location.height + "px",
      };
    },
    option() {
      return {
        customSymbol: this.widget.option.series[0].customSymbol,
        symbolMargin: this.widget.option.series[0].symbolMargin,
        symbolSize: this.widget.option.series[0].symbolSize,
      };
    },
    data() {
      return this.widget.data;
    },
    refresh() {
      return this.widget.service.timestamp;
    },
  },
  watch: {
    option: {
      handler(val) {
        this.widget.option.series[0].symbol = "image://" + val.customSymbol;
        this.widget.option.series[1].customSymbol = val.customSymbol;
        this.widget.option.series[1].symbol = "image://" + val.customSymbol;
        this.widget.option.series[1].symbolMargin = val.symbolMargin;
        this.widget.option.series[1].symbolSize = val.symbolSize;
      },
      deep: true,
    },
    data: {
      handler() {
        this.refreshWidgetInfo();
      },
      deep: true,
    },
    refresh: {
      handler() {
        this.refreshWidgetInfo();
      },
    },
  },
  mounted() {
    this.refreshWidgetInfo();
  },
  destroyed() {
    this.recoveryRenderObject();
  },
  methods: {
    refreshWidgetInfo() {
      this.recoveryRenderObject();
      this.render = renderWidgetData(this.widget, this.refreshWidgetData);
    },
    refreshWidgetData(data) {
      const option = this.widget.option;
      option.yAxis.data = data.map((item) => {
        return item.name;
      });
      let values = data.map((item) => {
        return item.value;
      });
      option.series[0].data = values;
      option.series[1].data = values;
    },
    recoveryRenderObject() {
      if (this.render && this.render.apiTimer) {
        clearInterval(this.render.apiTimer);
        this.render.apiTimer = null;
      }
      if(this.render && this.render.websocket) {
        this.render.websocket.doDisconnect();
      }
    },
  },
};
</script>